<!doctype html>
<!-- 讲座详情页面 -->
<!-- author: 豆豆 -->
<!-- 2020/6/30 -->
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover" />
		<script src="../../Common/js/lib/jquery-3.4.1.min.js"></script>
		<script src="../../Common/js/lib/materialize.min.js"></script>
		<script src="../../Common/js/tools.js"></script>
		<script src="../../Common/js/jump.js"></script>
		<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
		<link rel="stylesheet" href="../../Common/css/lib/materialize.min.css">
		<link rel="stylesheet" href="../../Common/css/ufun.css" />
		<link rel="stylesheet" href="../../Common/css/summernote-fix.css" />
		<link rel="stylesheet" href="../../Common/css/detail-page.css" />
		<style type="text/css">
			body {
				display: flex;
			}
			
			#NavBar,
			#QuesCard,
			#UserInfo {
				padding: 0 5vw;
			}

			#UserInfo {
				flex: none;
				height: 14vw;
				display: flex;
				align-items: center;
				padding: 1.5vw 5vw 0.5vw 5vw;
				background-color: var(--color-white);
			}
			
			.user-head-img {
				height: 10vw;
				width: 10vw;
				float: left;
				border-radius: 50%;
				border: 1px solid var(--color-gray-light);
				margin-right: 2.2vw;
			}

			.user-name {
				float: left;
				margin-right: 2vw;
				font-size: 4vw;
				font-weight: 300;
			}

			#QuesCard {
				background-color: var(--color-white);
				border: 1px solid var(--color-white);
			}

			#QuesTitleLine {
				margin-top: 2.6vw;
			}

			#QuesTitle {
				display: inline;
				font-weight: bold;
				font-size: 1.5rem;
				height: 1rem;
			}

			#Reward {
				height: 5.6vw;
				width: 14vw;
				border-radius: 1.5vw;
				float: right;
				margin-left: 1.7vw;
				font-weight: 600;
				font-size: 4vw;
				line-height: 6vw;
				color: var(--color-white);
				background-color: var(--color-yellow);
				text-shadow: 0 0 1px sandybrown;
			}

			#QuesTitleUnderline {
				height: 1vw;
				width: 27.7vw;
				border-radius: 0.5vw;
				background-color: var(--color-yellow);
			}

			#Tags {
				margin: 2.8vw auto;
				display: flex;
			}

			#Tags div {
				margin-right: 3.3vw;
				height: 7vw;
				padding: 0 1.5vw;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 0.8rem;
				border: 0.25vw solid var(--color-black);
				border-radius: 1.5vw;
			}

			#QuesFooter {
				margin: 3.2vw 0;
			}

			#QuesLooked {
				text-align: right;
				font-size: 3vw;
			}

			#QuesStatus {
				background-color: var(--color-gray-white);
				padding: 3.3vw 4.44vw;
			}

			#QuesText {
				margin: 2vw 0 3.3vw;
				word-wrap: break-word;
				white-space: pre-wrap;
			}

			#StatusLine {
				height: 6.6vw;
				text-align: center;
				font-size: 1.25rem;
				color: var(--color-white);
				border-radius: 1.5vw;
			}

			#HiddenSection {
				display: none;
			}
			
			.assign-btn {
				height: 5.6vw;
				width: 13.33vw;
				margin: 2.3vw 3.3vw 2.3vw 0;
				float: right;
				text-align: center;
				font-size: 3.5vw;
				font-weight: bolder;
				border: none;
				border-radius: 1.5vw;
			}
			
			.appl-card {
				display: block;
				margin: 3vw;
				padding: 3vw;
				border-radius: 2vw;
				font-weight: 300;
				height: 16vw;
				background-color: var(--color-white);
				border-bottom: 2px solid #F0F0F0;
			}
			
			.ans-card {
				padding: 3.3vw 4.44vw;
				background-color: var(--color-white);
				border-bottom: 1px solid var(--color-gray-white);
			}

			.ans-card .anser-info {
				height: 10vw;
				display: flex;
				align-items: center;
				margin-bottom: 3.3vw;
			}
			
			.ans-card .ans-text {
				word-break: break-all;
				white-space: pre-wrap;
			}
		</style>
	</head>

	<body>
		<header>
			<div id="Left" class="com-btn" onmouseup="ThisBack();">
				<i class="material-icons">keyboard_arrow_left</i>
			</div>
			<div id="Title">问题详情</div>
			<div id="Right" class="com-btn" onmouseup="showMenu();">
				<i class="material-icons">more_horiz</i>
			</div>
		</header>

		<div class="content flex">
			<!--用户展示区-->
			<section id="UserInfo">
				<img class="user-head-img circle" id="HeadImg">
				<div class="user-name" id="UserName">用户名</div>
			</section>
			<!--问题展示区-->
			<section id="QuesCard">
				<div id="QuesTitleLine">
					<p id="QuesTitle"> </p>
					<div class="right center">
						<div id="Reward"></div>
						<span style="color: var(--color-gray-medium);">悬赏</span>
					</div>
				</div>
				<div id="QuesTitleUnderline"></div>
				<div id="Tags">
					<div>山西大学</div>
				</div>
				<div id="QuesText" class="note-editor"></div>
				<div id="QuesFooter">
					<p class="gray-text" id="QuesLooked">
						0 浏览
					</p>
				</div>
			</section>
			<!--状态区-->
			<section id="QuesStatus">
				<div id="StatusLine" style="background-color: var(--color-gray-medium);">待回答</div>
			</section>
			<!--回答区-->
			<section id="QuesAns">

			</section>
			<!--HTML模板区-->
			<section id="HiddenSection" style="display: none;">
				<!--回答信息卡-->
				<div class="ans-card">
					<div class="anser-info">
						<img class="user-head-img">
						<span class="user-name"></span>
						<span class="gray-text" style="margin-left: auto;"></span>
					</div>
					<div class="ans-text note-editor">
						<!-- 回答内容 -->
					</div>
				</div>
				<!--抢答用户卡-->
				<div class="appl-card">
					<img src="" class="user-head-img">
					<button class="assign-btn theme-color theme-color-dark-bg">指定</button>
					<span class="user-name" style="line-height: 11vw;"></span>
					<span class="theme-color"></span>
				</div>
			</section>
		</div>
		<!--底部功能区-->
		<footer id="FooterBox">
			<div id="LikeBtn">
				<img src="./img/like.png" class="like-icon">
				<div>难题</div>
				<!-- <img src="./img/dislike.png" class="like-icon" style="float: right;"> -->
			</div>
			<div id="ReplyBtn" class="footer-btn">
				<img src="./img/accept.png">
				<span style>回复</span>
			</div>
			<div id="AcceptBtn" class="footer-btn">
				<img src="./img/accept.png">
				<span style>采纳</span>
			</div>
			<div id="ApplyBtn" class="footer-btn">
				<img src="./img/accept.png">
				<span style>抢答</span>
			</div>
			<!-- 收藏 -->
			<!-- <div style="margin-left: auto;">
					<img src="./img/save_norm.png" style="height: 8.3vw;">
				</div> -->
		</footer>
		<script>
			var userHash;
			var current;
			var phoneNo;
			var quesId;
			var reward;
			var theQues;
			var theAns;
			var isQuestioner = false;
			var isAnswerer = false;
			var InRefresh = false;

			function refreshPage() {
				DoWait();
				fetchQuestion();
				setTimeout(function() {
					if (IsWaiting) {
						plus.nativeUI.alert("请检查网络连接!", "错误");
						DontWait();
					}
					DoShow(current);
				}, 3000);
			}

			document.addEventListener('plusready', function() {
				GetStatusTop();
				userHash = plus.storage.getItem("userHash");
				current = plus.webview.currentWebview();
				quesId = current.quesId;
				refreshPage();
			});
			
			/**
			 * 从服务器获取问题数据和状态
			 * 根据问题状态填充页面并删减UI元素（主要是按钮）
			 */
			function fetchQuestion() {
				DoWait();
				// 获取问题数据以及状态
				CallAJAX("getQues", {
						"userHash": userHash,
						"quesId": quesId
					},
					function(data) {
						InRefresh = false;
						if (data["res"] != "ok")
							return;
						theQues = data["ques"];
						RefreshUserInfo(function(phoneNo1) {
							phoneNo = phoneNo1
							isQuestioner = (phoneNo == data["ques"]["quesQueserId"]);
							isAnswerer = (phoneNo == data["ques"]["quesAnserId"]);
							showQuesCard(data["ques"]);
							showStatus(data["ques"]["quesStatus"], data["ques"]["quesScored"]);
						});
					});
			}

			/**
			 * 根据返回的数据去填充问题描述的标题、标签、问题描述、悬赏金额、浏览数
			 * @param {*} ques 服务器返回问题数据
			 */
			function showQuesCard(ques) {
				ID("QuesTitle").innerText = ques["quesTitle"];
				ID("HeadImg").src = SERVER_LOC + ques["quesQueserHeadImgLoc"];
				ID("UserName").innerText = ques["quesQueserNick"];
				reward = ques["quesReward"];
				if (ques["quesReward"] != 0) {
					ID("Reward").innerText = ques["quesReward"];
				} else {
					ID("Reward").innerText = "无";
					ID("Reward").style.backgroundColor = "#999";
				}
				ID('UserInfo').addEventListener('click', function() {
					JumpToUserIndex(ques["quesQueserId"], "../../");
				});
				// 更新标签（最多显示三个标签）
				for (let i = 0; i < ques.quesTags.length && i < 3; i++) {
					if (ques.quesTags[i].trim() == "")
						continue;
					let tag = document.createElement("div");
					tag.innerText = ques.quesTags[i];
					ID("Tags").appendChild(tag);
				}
				ID("QuesText").innerHTML = ques["quesText"];
				ID("QuesLooked").innerText = ques["quesLookedCnt"] + " 浏览";
			}

			/**
			 * 根据问题状态更新状态栏和UI界面
			 * @param {*} status 服务器返回问题状态，字段含义参照文档
			 */
			function showStatus(status, scored) {
				// 更新状态栏
				let showMsg = "";
				if (status === 0) {
					showMsg = "正在招募作答者";
				} else if (status === 1) {
					showMsg = "正在等待解答";
				} else if (status === 2) {
					showMsg = "正在解答中";
				} else if (status === 3) {
					showMsg = "已关闭";
				} else if (status === 4) {
					showMsg = "已结束";
				}
				ID("StatusLine").innerText = showMsg;

				if (isQuestioner || isAnswerer) {
					if (isQuestioner && status == 0) {
						getAppls();
					}
				} else {
					if (status != 0) {
						plus.nativeUI.toast("您当前处于旁观模式");
					}
				}
				if (status >= 1) {
					getAnswers();
				} else {
					DoShow(current);
				}
				showBtns(status);
				if (status == 4 && !scored && isQuestioner) {
					JumpToQuesScore(quesId);
				}
			}

			/**
			 * 根据问题状态和isQuestioner删除顶部用户信息和底部按钮
			 * @param {*} status 问题状态
			 */
			function showBtns(status) {
				ID("LikeBtn").onclick = like;
				ID("ApplyBtn").onclick = apply4Ans;
				ID("AcceptBtn").onclick = accept;
				ID("ReplyBtn").onclick = reply;
				// 提问者视角
				if (isQuestioner) {
					ID("LikeBtn").style.display = "inline-flex";
					switch (status) {
						case 0:
							break;
						case 1:
							break;
						case 2:
							ID("AcceptBtn").style.display = "inline-flex";
							ID("ReplyBtn").style.display = "inline-flex";
							break;
						case 3:
							ID("AcceptBtn").style.display = "inline-flex";
							ID("AcceptBtn").classList.add("btn-mute");
							break;
						case 4:
							break;
						default:
					}
				}
				// 回答者视角
				else if (isAnswerer) {
					ID("LikeBtn").style.display = "inline-flex";
					switch (status) {
						case 0:
							ID("ApplyBtn").style.display = "inline-flex";
							break;
						case 1:
							ID("ReplyBtn").style.display = "inline-flex";
							break;
						case 2:
							ID("ReplyBtn").style.display = "inline-flex";
							break;
						case 3:
							break;
						case 4:
							break;
						default:
					}
				}
				// 旁观者视角
				else {
					ID("LikeBtn").style.display = "inline-flex";
					switch (status) {
						case 0:
							ID("ApplyBtn").style.display = "inline-flex";
							break;
						case 1:
							break;
						case 2:
							break;
						case 3:
							break;
						case 4:
							break;
						default:
					}
				}
			}

			/**
			 * 从服务器获取问答日志
			 */
			function getAnswers() {
				CallAJAX("getQuesLog", {
						userHash: userHash,
						quesId: quesId
					},
					function(data) {
						DoShow(current);
						if (data["res"] != "ok")
							return;
						ID("QuesAns").innerHTML = "";
						theAns = data["quesLogs"];
						for (let i = 0; i < data["quesLogs"].length; i++) {
							setTimeout(function() {
								showAnswer(data["quesLogs"][i]);
							}, 20 * i);
						}
					},
					function() {
						DoShow(current);
					});
			}

			/**
			 * 从隐藏的功能区复制一份答案展示card，根据服务器返回的数据填充答案展示卡并添加到QuesAns中
			 * @param {*} quesLog 单个答案数据
			 */
			function showAnswer(quesLog) {
				// 展示每个答案
				let card = QUERY("#HiddenSection > .ans-card")[0].cloneNode(true);
				card.children[0].children[0].src = SERVER_LOC + quesLog["quesLogUserHeadImgLoc"];
				card.children[0].children[0].addEventListener('click', function() {
					JumpToUserIndex(quesLog["quesLogUserId"]);
				});
				// 用户名
				card.children[0].children[1].innerText = quesLog["quesLogUserNick"];
				// 答题时间
				card.children[0].children[2].innerText = String2Date(quesLog["quesLogT"], true);
				// 答案
				card.children[1].innerHTML = quesLog["quesLogText"];
				ID("QuesAns").appendChild(card);
			}

			/**
			 * 从服务器获取抢答者信息并展示抢答者信息
			 */
			function getAppls() {
				CallAJAX("getAppls", {
						userHash: userHash,
						quesId: quesId
					},
					function(data) {
						DoShow(current);
						if (data["res"] != "ok" || data["appls"] == null)
							return;
						ID("QuesAns").innerHTML = "";
						for (let i = 0; i < data["appls"].length; i++)
							showAppl(data["appls"][i]);
					},
					function() {
						DoShow(current);
					});
			}

			/**
			 * 展示抢答者信息
			 * @param {} appl 单个抢答者信息
			 */
			function showAppl(appl) {
				let card = QUERY("#HiddenSection > .appl-card")[0].cloneNode(true);
				card.children[0].src = SERVER_LOC + appl["applyUserHeadImgLoc"];
				card.children[0].addEventListener('click', function() {
					JumpToUserIndex(appl["applyUserId"], "../../");
				});
				// 指定
				card.children[1].addEventListener("click", () => {
					assign(appl["applyUserId"]);
				});
				// 用户名
				card.children[2].innerText = appl.applyUserNick;
				card.children[2].addEventListener('click', function() {
					JumpToUserIndex(appl["applyUserId"], "../../");
				});
				// 评分
				// 信息
				document.getElementById("QuesAns").appendChild(card);
			}

			/**
			 * 抢答按钮回调函数，往服务器发送抢答请求
			 */
			function apply4Ans() {
				CallAJAX("apply4Ans", {
						userHash: userHash,
						quesId: quesId
					},
					function(res) {
						if (res.res != "ok") {
							plus.nativeUI.toast("您不能多次抢答,请耐心等待提问者指定");
						} else {
							plus.nativeUI.toast("抢答成功,请耐心等待提问者指定");
						}
						ID('ApplyBtn').classList.add('btn-mute');
						ID('ApplyBtn').onclick = null;
					},
					function() {
						plus.nativeUI.alert("不能抢答……", "错误");
					});
			}

			/**
			 * 指定按钮回调函数
			 * @applId 指定用户Id
			 */
			function assign(applId) {
				CallAJAX("assign", {
					userHash: userHash,
					quesId: quesId,
					assign2UserId: applId
				},
				function(data) {
					if (data["res"] === "ok") {
						plus.nativeUI.toast("已指定回答者, 请耐心等待解答");
						plus.webview.currentWebview().hide();
						location.reload();
					}
				});
			}

			function accept() {
				CallAJAX("closeQues", {
					userHash: userHash,
					quesId: quesId,
				},
				function(data) {
					if (data["res"] === "ok") {
						plus.nativeUI.toast("回答已被采纳, 问题已结束");
						plus.webview.currentWebview().hide();
						location.reload();
					}
				});
			}

			function like() {
				CallAJAX("likeQues", {
					userHash: userHash,
					quesId: quesId,
				},
				function(data) {
					if (data["res"] != "ok")
						return;
					ID('LikeBtn').classList.add('btn-mute');
					ID('LikeBtn').onclick = null;
				});
			}

			function reply() {
				var lastLog;
				var i = -1;
				for (i = theAns.length - 1; i >= 0; i--)
					if (theAns[i]["quesLogUserId"] != phoneNo)
						break;
				if (i != -1) {
					lastLog = {
						"quesLogText": theAns[i]["quesLogText"],
						"uHeadImgLoc": theAns[i]["quesLogUserHeadImgLoc"],
						"uNick": theAns[i]["quesLogUserNick"]
					};
				} else {
					lastLog = {
						"quesLogText": theQues["quesText"],
						"uHeadImgLoc": theQues["quesQueserHeadImgLoc"],
						"uNick": theQues["quesQueserNick"]
					};
				}
				plus.webview.create(
					'reply.html',
					'Reply', {}, {
						"quesId": quesId,
						"lastLog": lastLog
					}
				);
			}

			function showMenu() {
				JumpToMenu({
					"entityType": 0,
					"entityId": quesId,
					"entityTitle": theQues['quesTitle'],
					"entityContent": "快来查看回答吧!",
					"isAuthor": isQuestioner,
				});
			}

			function edit() {
				current.append(plus.webview.create(
					'edit.html',
					'QuesEdit', {}, {
						'quesId': quesId,
						'quesTitle': ID('QuesTitle').innerText,
						'quesContent': ID('QuesText').innerHTML,
						'quesReward': reward,
					}
				));
			}

			function remove() {
				CallAJAX("changeQues", {
					"userHash": userHash,
					"quesId": quesId,
					"action": "delete"
				}, function(data) {
					if (data["res"] == "ok") {
						plus.nativeUI.toast('问题删除成功');
						ThisClose();
					} else {
						plus.nativeUI.alert('请检查网络设置', '删除失败');
					}
				}, function() {
					plus.nativeUI.alert('请检查网络设置', '删除失败');
				});
			}
		</script>
	</body>
</html>
